package models;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.OneToMany;

import play.data.validation.Required;
import play.db.jpa.Model;

@Entity
public class ShoppingCart extends Model {	

	@OneToMany
	public List<ShoppingCartLine> lines;

	@Required
	public boolean isBilled;

	public ShoppingCart(boolean isBilled) {
		super();
		this.lines = new LinkedList<ShoppingCartLine>();
		this.isBilled = isBilled;
		create();
	}

	public void addLine(ShoppingCartLine line) {
		boolean inTheList = false;
		for (ShoppingCartLine l : this.lines) {
			if (l.product.equals(line.product)) {
				l.quantity += line.quantity;
				l.save();
				inTheList = true;
				break;
			}
		}
		if (!inTheList) {
			this.lines.add(line);
		}
		this.save();
	}

	public void decrementLine(ShoppingCartLine line) {
		if (line.quantity > 1) {
			line.quantity = line.quantity - 1;
			line.save();
		} else {
			this.lines.remove(line);
		}
		this.save();
	}

	public int getCalories() {
		int calories = 0;
		for (ShoppingCartLine line : this.lines) {
			calories += line.getCalories();
		}
		return calories;
	}

	public double getPrice() {
		double price = 0;
		for (ShoppingCartLine line : this.lines) {
			price += line.getPrice();
		}
		return price;
	}
}
